﻿using SX.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ly.Scheduler.Common
{
    public   class JobActionService: BaseService
    {
        public JobActionService() : base("LYJobs", "j_Action", "作业动作")
        {

        }
        public JobAction GetUnExecAction() {
           var jobAction =   db.Sql(@"SELECT TOP 1 [Id] ,[JobId],[Action] ,[CreateTime] ,[JobState] ,[ActionResult] ,[ExecTime] ,[CompleteTime]
  FROM [dbo].[j_Action] WHERE JobState = 0").QuerySingle<JobAction>();
            if (jobAction != null)
            {
                var result = db.Sql("update j_Action set  JobState = 1, ExecTime=getdate() where JobState = 0 and id=" + jobAction.Id + "").Execute();
                if (result != 0)
                {
                    return jobAction;
                }
            }
            return jobAction;
        }
        /// <summary>
        /// 完成动作
        /// </summary>
        /// <param name="id"></param>
        /// <param name="actionresult"></param>
        public void CompleteAction(long id, string actionresult) {
            var result = db.Sql("update j_Action set  JobState = 2, ,ExecTime=getdate(),ActionResult=@ActionResult  where JobState = 1 and id=@id")
                .Parameter("id", id, SX.Data.DataTypes.Int64)
                .Parameter("ActionResult", actionresult, SX.Data.DataTypes.StringFixedLength).Execute(); 
        }
    }

    /// <summary>
    /// 作业动作
    /// </summary>
    public class JobAction {
        public long Id { get; set; }
        public Guid JobId { get; set; }

        public string Action { get; set; }

        /// <summary>
        /// 0 未执行 1 已执行 2 执行完成 
        /// </summary>
        public int JobState { get; set; }

        /// <summary>
        /// 执行结果
        /// </summary>
        public string ActionResult { get; set; }

        /// <summary>
        /// 执行时间
        /// </summary>
        public DateTime? ExecTime { get; set; }

        /// <summary>
        /// 完成时间
        /// </summary>
        public DateTime? CompleteTime { get; set; }
    }
}
